from PySide6.QtWidgets import QWidget
from PySide6.QtGui import QPaintEvent, QPixmap, QPainter
from PySide6.QtCore import Qt


class ImageWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__()
        if parent is not None:
            self.setParent(parent)
        # 图片路径
        self.image_path = ''

    # 设置图片路径
    def setImagePath(self, path):
        # 设置要加载图片的路径
        self.image_path = path
        # 更新窗口（会自动调用绘图事件）
        self.update()

    # 重写父类的绘图事件
    def paintEvent(self, event: QPaintEvent) -> None:
        # 实例化一个画笔
        painter = QPainter(self)
        # 如果图片路径不存在则终止绘制
        if self.image_path == '':
            return
        # 根据图片路径加载图片
        pixmap = QPixmap(self.image_path)
        # 设置图片的缩放
        pixmap = pixmap.scaled(self.size(), Qt.AspectRatioMode.KeepAspectRatio,
                               Qt.TransformationMode.SmoothTransformation)
        # 设置画笔的抗锯齿
        painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
        # 使画笔开始绘制图片
        painter.drawPixmap(0, 0, pixmap)
